﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using BasicHttpSohu;
using System.Windows;
using WeiBeeCommon.Core;

namespace SohuWeiBoBatchTool
{
    class Program
    {
        static List<SohuAccount> sohuaccountlist = new List<SohuAccount>();
        private static AutoResetEvent _autoEvent;

        static void Main()
        {
            Console.Write("用户名:");
            _username = Console.ReadLine();
            Console.Write("密码:");
            _pwd = Console.ReadLine();
            cookiestring = Application.GetCookie(new Uri("http://t.sohu.com"));
            _autoEvent = new AutoResetEvent(false);
            Thread t = new Thread(VisitPublicTimelineUsers);
            t.Start();
            _autoEvent.WaitOne();
        }
        static string cookiestring;
        static private string _username;
        static private string _pwd;
        /// <summary>
        /// 通过访问Public Timeline用户的页面，增加被关注的机会。
        /// </summary>
        private static void VisitPublicTimelineUsers()
        {
            List<BasicHttpSohu.Status> listStatus = ApiService.PublicTimeline(_username, _pwd);
            _userIdList = new List<string>();
            foreach (var status in listStatus)
            {
                _userIdList.Add(status.user.id);
            }
            _userIndex = 0;
            
            _webClient = new WebClientWithCookie(cookiestring);
            
            _webClient.DownloadStringCompleted += WebClientDownloadStringCompleted;
            _webClient.DownloadStringAsync(new Uri(string.Format(Urlformater, _userIdList[_userIndex])));
        }

        static void WebClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            Console.WriteLine(string.Format(Urlformater, _userIdList[_userIndex]) + " done.");
            _userIndex++;
            if (_userIndex < _userIdList.Count)
            {
                _webClient.DownloadStringAsync(new Uri(string.Format(Urlformater, _userIdList[_userIndex])));
            }
            else
            {
                _autoEvent.Set();
            }
        }

        const string Urlformater = "http://t.sohu.com/u/{0}";
        private static WebClient _webClient;
        private static int _userIndex;
        private static List<string> _userIdList;

        #region 多账号粉一人
        /// <summary>
        /// 多人粉一人，被粉人ID从键盘输入
        /// </summary>
        public static void MultiUserFollowOneUser()
        {
            try
            {
                ReadAccounts();
                string followId = GetFollowId();
                BatchDoFollow(followId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error {0}, Call Statck {1}", ex.Message, ex.StackTrace);
            }
        }

        private static void BatchDoFollow(string followId)
        {
            int accessLimit = 0;
            try
            {
                BasicHttpSohu.Hash hashTheStrangeName = ApiService.RateLimitStatus(sohuaccountlist[0].Passport, sohuaccountlist[1].Password);
                Console.WriteLine("{0},{1},{2}", hashTheStrangeName.hourly_limit, hashTheStrangeName.remaining_hits, hashTheStrangeName.reset_time_in_seconds);
                accessLimit = hashTheStrangeName.remaining_hits;
            }
            catch
            {
                Console.WriteLine("剩余API调用不足，退出");
                return;
            }
            for (int i = 0; i < accessLimit && i < sohuaccountlist.Count; i++)
            {
                try
                {
                    ApiService.Create(sohuaccountlist[i].Passport, sohuaccountlist[i].Password, followId);
                    Console.WriteLine("{0} 关注成功", sohuaccountlist[i].Passport);
                }
                catch
                {
                    Console.WriteLine("{0} 关注失败", sohuaccountlist[i].Passport);
                }
            }
        }

        private static string GetFollowId()
        {
            Console.Write("请输入你想关注的SOHU微博用户ID:");
            return Console.ReadLine();
        }

        private static void ReadAccounts(string filename="accounts.txt")
        {
            Console.WriteLine("从文件 {0} 中读取账号", filename);
            var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
            var streamReader = new StreamReader(fileStream);
            streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
            string strLine = streamReader.ReadLine();
            while (strLine != null)
            {
                // Console.WriteLine("adding " + strLine);
                char[] separator = { ' ', ',' };
                var account = strLine.Split(separator);
                Console.WriteLine("SOHU账号 {0}", account[0]);
                sohuaccountlist.Add(new SohuAccount(account[0], account[1]));
                strLine = streamReader.ReadLine();
            }
            streamReader.Close();
        }
        #endregion
    }
}
